from tkinter import *
import tkinter as tk
import os
from urllib.request import urlretrieve
from selenium import webdriver
#http://music.163.com/song/media/outer/url?id={}.mp3
def load(item):
   song_id = item['song_id']
   song_name = item['song_name']
   song_url = 'http://music.163.com/song/media/outer/url?id={}.mp3'.format(song_id)
   #os模块创建保存文件
   os.makedirs('music',exist_ok=True)
   path = 'music\{}.mp3'.format(song_name)
   #文本框滑动
   text.see(END)
   #更新
   text.update()
   urlretrieve(song_url,path)
   text.insert(END,'下载完毕：{},请试听。。。。。'.format(song_name))
   #文本框滑动
   text.see(END)
   #更新
   text.update()

def music():
    name = entry.get()
    url = 'https://music.163.com/#/search/m/?id=2460477771&s={}&type=1'.format(name)

#模拟浏览器
    driver = webdriver.Chrome()
    driver.get(url=url)
    driver.switch_to.frame('g_iframe')
    #获取id
    req = driver.find_element_by_id('m-search')
    a_id=req.find_element_by_xpath('.//div[@class="item f-cb h-flag  "]/div[2]//a').get_attribute('href')
    print(a_id)
    song_id = a_id.split('=')[-1]
    print(song_id)
    song_name=req.find_element_by_xpath('.//div[@class="item f-cb h-flag  "]/div[2]//b').get_attribute('title')
    print(song_name)
    item = {}
    item['song_name']=song_name
    item['song_id'] = song_id
    load(item)


import tkinter as tk
root = tk.Tk()
root.title('网易云 歌曲下载')
#root.geometry()
root['bg']='lavender'
root.geometry('650x500+450+110')
#输入框
tk.Label(root,text='请输入要下载的歌曲：',bg='lavender',font=('华文行楷',20)).place(x=50,y=70)

# 设置搜索框
entry = tk.Entry(root,bg='lavender',font=('华文行楷',15),width=30,bd=4)
entry.place(x=300,y=70)

# 创建文本内容
text=tk.Text(root,bg='pink',font=('宋体',16),bd=4)
text.place(x=0, y=180, height=380, width=650)

# 设置开始下载按钮
b= tk.Button(root, text='下载歌曲', bg='lavender',font=('华文行楷',15),bd=4,command=music)
b.place(x=300,y=110, height=35, width=100)

#退出按钮
b1=tk.Button(root,text='退出',bg='lavender',font=('华文行楷',15),command=root.quit)
b1.place(x=460,y=110, height=35, width=60)
#显示界面
root.mainloop()





















